package com.jyh.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.jyh.config.BaseAction;
import com.jyh.config.datasource.TargetDataSource;
import com.jyh.db.entity.JyhChannelList;
import com.jyh.db.entity.JyhChannelListExample;
import com.jyh.db.mapper.JyhChannelListMapper;
import com.jyh.dbUser.dao.PersonInfoDao;
import com.jyh.util.CheckIdCardUtils;
import com.jyh.util.Constant;
import com.jyh.util.StringUtils;

@Service
public class PersonService extends BaseAction {
	@Autowired
	private PersonInfoDao personInfoDao;
	@Autowired
	private ButtonService buttonService;
	@Autowired
	private ZhimaService zhimaService;
	@Autowired
	private BorrowStateService borrowStateService;
	@Autowired
	private JyhChannelListMapper JyhChannelListMapper;

	/**
	 * 列表信息
	 * 
	 * @param request
	 * @param session
	 * @return
	 */
	@TargetDataSource(name = "user")
	public ModelAndView find(HttpServletRequest request, HttpSession session) {
		ModelAndView mv = new ModelAndView("user/userInfo");
		String userNumber = request.getParameter("userNumber");
		String userName = request.getParameter("userName");
		String phoneNumber = request.getParameter("phoneNumber");
		String registerTimeStart = request.getParameter("registerTimeStart");
		String registerTimeEnd = request.getParameter("registerTimeEnd");
		String registerSource = request.getParameter("register");
		String channel= request.getParameter("channelList");
		String page = request.getParameter("currentPage");// 传过来的页数
		int lineSize = 20; // 每页显示记录20条数
		int pageCount = 0; // 总页数
		int count = 0; // 数据总数
		int currentPage = 1; // 当前是第几页,默认是第一页
		if (page == null || "1".equals(page)) {
		} else {
			currentPage = Integer.parseInt(page); // 当前是第几页,默认是第一页
		}
		if (currentPage < 1) {
			currentPage = 1;
		}
		String limitSql = " limit " + (currentPage - 1) * lineSize + "," + lineSize;
		
	//	String sql = "SELECT * FROM jyh_person j1 LEFT JOIN jyh_channel_list j2 ON j1.channelNumber = j2.channelNumber WHERE 1=1 ";
		String sql = "SELECT j1.userNumber,j1.userName,j1.userIDCard,j1.phoneNumber,j1.deviceType,j1.logtime,j2.channelNumber,j2.channelName,j2.generalize_id FROM jyh_person j1 LEFT JOIN jyh_channel_list j2 ON j1.channelNumber = j2.channelNumber WHERE 1=1 ";
		String sql1 = "SELECT count(1) as count  FROM jyh_person j1 LEFT JOIN jyh_channel_list j2 ON j1.channelNumber = j2.channelNumber WHERE 1=1 ";
		if (StringUtils.isNotNull(userNumber)) {
			sql = sql + " and userNumber='" + userNumber + "'";
			sql1 = sql1 + " and userNumber='" + userNumber + "'";
		}
		if (StringUtils.isNotNull(userName)) {
			sql = sql + " and userName='" + userName + "'";
			sql1 = sql1 + " and userName='" + userName + "'";
		}
		if (StringUtils.isNotNull(phoneNumber)) {
			sql = sql + " and phoneNumber='" + phoneNumber + "'";
			sql1 = sql1 + " and phoneNumber='" + phoneNumber + "'";
		}
		if (StringUtils.isNotNull(registerTimeStart)) {
			sql = sql + " and logtime>='" + registerTimeStart + "'";
			sql1 = sql1 + " and logtime>='" + registerTimeStart + "'";
		}
		if (StringUtils.isNotNull(registerTimeEnd)) {
			sql = sql + " and logtime<='" + registerTimeEnd + "'";
			sql1 = sql1 + " and logtime<='" + registerTimeEnd + "'";
		}
		if (StringUtils.isNotNull(registerSource)) {
			if (registerSource.equals("Android")) {registerSource = "0";}
			if (registerSource.equals("IOS")) {registerSource = "1";}
			if (registerSource.equals("WEB")) {registerSource = "2";}
			if (registerSource.equals("WAP")) {registerSource = "3";}
			sql = sql + " and deviceType='" + registerSource + "'";
			sql1 = sql1 + " and deviceType='" + registerSource + "'";
		}
		if (StringUtils.isNotNull(channel)) {
			sql = sql + " and channelName='" + channel + "'";
			sql1 = sql1 + " and channelName='" + channel + "'";
		}


		Map<String, Object> map = personInfoDao.getMap(sql1);
		count = Integer.parseInt(map.get("count") + "");
		if(count<=lineSize){
			limitSql = " limit 0," + lineSize;
		}
		sql =  sql + " ORDER BY logtime DESC " + limitSql;
		List<Map<String, Object>> list = personInfoDao.getlist(sql);
		
		int temp = count / lineSize; // 取商
		int tem2 = count % lineSize;// 取余数
		if (tem2 > 0 && tem2 < lineSize && temp > 0) {
			pageCount = count / lineSize + 1; // 总页数
		} else if (tem2 == 0 && temp > 0) {
			pageCount = temp;
		} else {
			pageCount = 1; // 总页数
		}
		if (currentPage >= pageCount) {
			currentPage = pageCount;
		}
		mv.addObject("pageCount", pageCount);
		mv.addObject("currentPage", currentPage);
		mv.addObject("count", count);

		
		/* 注册来源 */
		Map<String, String> mapReqS = new HashMap<>();
		for (int i = 0; i < list.size(); i++) {
			String deviceType = (String) list.get(i).get("deviceType");
			if (StringUtils.isNotNull(deviceType)) {
				if (deviceType.equals("0")) {
					mapReqS.put("source", "Android");
					list.get(i).putAll(mapReqS);
				}
				if (deviceType.equals("1")) {
					mapReqS.put("source", "IOS");
					list.get(i).putAll(mapReqS);
				}
				if (deviceType.equals("2")) {
					mapReqS.put("source", "WEB");
					list.get(i).putAll(mapReqS);
				}
				if (deviceType.equals("3")) {
					mapReqS.put("source", "WAP");
					list.get(i).putAll(mapReqS);
				}
			}
		}
		/* 渠道编号 */
		for (int i = 0; i < list.size(); i++) {
			String channelNumber = (String) list.get(i).get("channelNumber");
			if (StringUtils.isNotNull(channelNumber)) {
				String sqlList = "SELECT channelName,generalize_id FROM jyh_channel_list  WHERE channelNumber = '"
						+ channelNumber + "'";
				List<Map<String, Object>> channelList = personInfoDao.getlist(sqlList);
				String channelName = (String) channelList.get(0).get("channelName");
				String generalize_id = (String) channelList.get(0).get("generalize_id");
				String subGeneralize_id = generalize_id.substring(0, 4);
				String channelNameFid = "";
				if (StringUtils.isNotNull(subGeneralize_id)) {
					String sqlList2 = "SELECT channelName,generalize_id FROM jyh_channel_list  WHERE generalize_id = '"
							+ subGeneralize_id + "'";
					List<Map<String, Object>> channelList2 = personInfoDao.getlist(sqlList2);
					channelNameFid = (String) channelList2.get(0).get("channelName");
					
				}
				Map<String, String> mapReq = new HashMap<>();
				mapReq.put("channel", channelNameFid.concat("-" + channelName));
				list.get(i).putAll(mapReq);

			}

		}
		/* 用户确认借款（生成订单）后，借款申请中由0变成1000 */
		Map<String, String> mapReqO = new HashMap<>();
		for (int i = 0; i < list.size(); i++) {
			String userNo = (String) list.get(i).get("userNumber");
			String state = borrowStateService.borrowState(userNo);
			if (state.equals("clear")) {
				mapReqO.put("borrow", "0");
				mapReqO.put("borrowPut", "0");
				list.get(i).putAll(mapReqO);
			}
			else if (state.equals("order")) 
			{
				mapReqO.put("borrow", "1000");
				mapReqO.put("borrowPut", "0");
				list.get(i).putAll(mapReqO);
			}
			else if (state.equals("put")) 
			{
				mapReqO.put("borrow", "0");
				mapReqO.put("borrowPut", "1000");
				list.get(i).putAll(mapReqO);
			} 
			else {
				mapReqO.put("borrow", "0");
				mapReqO.put("borrowPut", "0");
				list.get(i).putAll(mapReqO);
			}
		}
		/* 注册来源List */
		List<Object> register = new ArrayList<>();
		Map<String, Object> mapreg0 = new HashMap<>();
		Map<String, Object> mapreg1 = new HashMap<>();
		Map<String, Object> mapreg2 = new HashMap<>();
		Map<String, Object> mapreg3 = new HashMap<>();
		mapreg0.put("register","Android");
		mapreg1.put("register","IOS");
		mapreg2.put("register","WEB");
		mapreg3.put("register","WAP");
		register.add(mapreg0);
		register.add(mapreg1);
		register.add(mapreg2);
		register.add(mapreg3);
		
		String register2 ="";
		if (StringUtils.isNotNull(registerSource)) {
			switch (registerSource) {
			case "0":
				register2 = "Android";
				break;
			case "1":
				register2 = "IOS";
				break;
			case "2":
				register2 = "WEB";
				break;
			case "3":
				register2 = "WAP";
				break;
			default:
				break;
			}
		}
		list = (List<Map<String, Object>>) buttonService.getTableButton(2, "userNumber", jsonOutSimplify(list),session);
		mv.addObject("list", list);
		mv.addObject("register", register);
		mv.addObject("userNumber", userNumber);
		mv.addObject("userName", userName);
		mv.addObject("phoneNumber", phoneNumber);
		mv.addObject("registerTimeStart", registerTimeStart);
		mv.addObject("registerTimeEnd", registerTimeEnd);
		mv.addObject("channel", channel);
		mv.addObject("register2", register2);
		return mv;
	}
	/**
	 * 获取页面筛选--渠道列表
	 */
	@TargetDataSource(name = "user")
	public ModelAndView getSelectData(ModelAndView mv) {
		// 获取渠道列表
		List<JyhChannelList> channelList = JyhChannelListMapper.selectByExample(new JyhChannelListExample());
		mv.addObject("channelList", channelList);
		logger.info("获取渠道列表JyhChannelList={}",JSONObject.toJSONString(channelList));
		return mv;
	}

	/**
	 * 个人基础信息
	 * 
	 * @param request
	 * @param session
	 * @return
	 */
	@TargetDataSource(name = "user")
	public ModelAndView findPersonInfo(HttpServletRequest request, HttpSession session) {
		ModelAndView mv = new ModelAndView("user/detailInfo");

		String userNumber = request.getParameter("userNumber");
		String sql = "SELECT j1.userNumber,j1.phoneNumber,j1.userIDCard,j1.userName,j2.livingCity,j2.livingProvinces,"
				+ "j2.detailedAddress,j2.QQNo,j3.listExplain AS educational,CASE marriage WHEN 1 THEN N'未婚' WHEN 2 THEN N'已婚'WHEN 3 "
				+ "THEN N'丧偶' ELSE N'未知' END marriage FROM jyh_person j1 LEFT JOIN jyh_person_info j2 ON j1.userNumber=j2.userNumber "
				+ "LEFT JOIN jyh_down_list j3 ON j2.educational=j3.listNo WHERE 1=1 ";
		if (StringUtils.isNotNull(userNumber)) {
			sql = sql + " and j1.userNumber='" + userNumber + "'";
		}
		String sql2 = "SELECT userIDCard FROM jyh_person WHERE 1=1 ";
		if (StringUtils.isNotNull(userNumber)) {
			sql2 = sql2 + " and userNumber='" + userNumber + "'";
		}
		Map<String, Object> map = personInfoDao.getMap(sql);
		List<Map<String, Object>> list2 = personInfoDao.getlist(sql2);
		if (list2 != null && list2.size() >= 0) {
			Map<String, Object> aa = list2.get(0);
			if (StringUtils.isNotNull(String.valueOf(aa.get("userIDCard")))) {
				String idcard = String.valueOf(aa.get("userIDCard"));
				String sex = CheckIdCardUtils.getGenderByIdCard(idcard);
				String birDate = CheckIdCardUtils.getBirthByIdCard(idcard);
				int age = CheckIdCardUtils.getAgeByIdCard(idcard);
				map.put("sex", sex);
				map.put("birDate", birDate);
				map.put("age", age);
			}

		}

		map.putAll(workInfo(userNumber));
		map.putAll(contactInfo(userNumber));
		map.putAll(bankCardInfo(userNumber));
		map.putAll(authInfo(userNumber));
		System.out.println("=============" + bankCardInfo(userNumber));
		List<Map<String, Object>> lis = new ArrayList<>();
		lis.add(map);

		mv.addObject("list", lis);
		return mv;

	}

	/**
	 * 工作信息 TODO
	 */
	public Map<String, Object> workInfo(String userNumber) {
		String sql = "SELECT j1.companyName,j1.companyProvinces,j1.companyCity,j1.companyAddress,j1.companyTelephone,"
				+ "j1.salaryDay,j2.listExplain AS monthIncome,j3.listExplain AS occupation FROM jyh_work_info j1 LEFT JOIN jyh_down_list j2 ON "
				+ "j1.monthIncome=j2.listNo LEFT JOIN jyh_down_list j3 ON j1.occupation=j3.listNo WHERE 1=1 ";
		if (StringUtils.isNotNull(userNumber)) {
			sql = sql + " and j1.userNumber='" + userNumber + "'";
		}
		Map<String, Object> map = personInfoDao.getMap(sql);

		return map;
	}

	/**
	 * 联系人信息
	 */
	public Map<String, Object> contactInfo(String userNumber) {
		String sql = "SELECT RelativesName,RelativesPhoneNo,friendName,friendPhoneNo,CASE directRelatives WHEN 1 "
				+ "THEN N'父母' WHEN 2 THEN N'配偶'WHEN 3 THEN N'兄弟姐妹' ELSE N'未知' END directRelatives,CASE friendColleague "
				+ "WHEN 1 THEN N'同学' WHEN 2 THEN N'同事'WHEN 3 THEN N'朋友' ELSE N'未知' END friendColleague FROM jyh_contact_info WHERE 1=1 ";
		if (StringUtils.isNotNull(userNumber)) {
			sql = sql + " and userNumber='" + userNumber + "'";
		}
		Map<String, Object> map = personInfoDao.getMap(sql);

		return map;
	}

	/**
	 * 银行卡信息 list<map>
	 */
	@TargetDataSource(name = "user")
	public Map<String, Object> bankCardInfo(String userNumber) {
		String sql = "SELECT j1.cardholder,j1.bankCard,j2.bankName,CASE binding WHEN 1 THEN N'已经授' WHEN 0 THEN N'未授权' ELSE N'未知' "
				+ "END binding FROM jyh_bank_card j1 LEFT JOIN jyh_bank_list j2 ON j1.accountBank=j2.listNo WHERE 1=1 ";
		if (StringUtils.isNotNull(userNumber)) {
			sql = sql + " and j1.userNumber='" + userNumber + "'";
		}
		List<Map<String, Object>> listMap = personInfoDao.getListMap(sql);
		Map<String, Object> map = new HashMap<>();
		map.put("listmap", listMap);
		return map;
	}

	/**
	 * 认证信息
	 */

	public Map<String, Object> authInfo(String userNumber) {
		String sql = "SELECT  CASE holdCardPic WHEN 0 THEN N'未认证' WHEN 2 THEN N'认证成功 ' WHEN 4 THEN N'认证失败'  "
				+ "ELSE N'未知' END idCardZ FROM jyh_audit_state WHERE 1=1 ";
		if (StringUtils.isNotNull(userNumber)) {
			sql = sql + " and userNumber='" + userNumber + "'";
		}

		Map<String, Object> map = personInfoDao.getMap(sql);

		String sql2 = "SELECT phoneNumber as phone,CASE state WHEN 0 THEN N'未认证' WHEN 1 THEN N'已认证 'WHEN 2 THEN N'认证过期' ELSE N'未知' "
				+ "END operator  FROM jyh_phone_carrier WHERE 1=1 ";
		if (StringUtils.isNotNull(userNumber)) {
			sql2 = sql2 + " and userNumber='" + userNumber + "'";
		}
		Map<String, Object> map2 = personInfoDao.getMap(sql2);

		String sql3 = "SELECT userIDCard FROM jyh_person WHERE 1=1  ";
		if (StringUtils.isNotNull(userNumber)) {
			sql3 = sql3 + " and userNumber='" + userNumber + "'";
		}

		Map<String, Object> map3 = personInfoDao.getMap(sql3);
		Map<String, Object> map4 = new HashMap<>();
		String userIDCard = String.valueOf(map3.get("userIDCard"));
		if (StringUtils.isNotNull(userIDCard)) {
			map4 = zhimaService.userCardInfo(userIDCard);
		}

		Map<String, Object> maplis = new HashMap<>();
		maplis.putAll(map);
		maplis.putAll(map2);
		maplis.putAll(map4);
		return maplis;

	}

}
